package cc.fs.study.smart_app;

import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import java.io.File;

/**
 * 增量更新 https://github.com/JackCho/AndroidPatchUpdate
 * 工具 SmartUpdateTool
 */
class SmartUpdate {
    //加载so库
    static {
//        System.loadLibrary("ApkPatchLibrary");
    }

    private final String TAG = "SmartUpdate";
    private PatchTask pathTask;
    private SmartCallback callback;

    /**
     * @param callback 结果callback
     */
    public SmartUpdate(SmartCallback callback) {
        this.callback = callback;
        this.pathTask = new PatchTask();
    }

    /**
     * @param oldApkPath 旧安装包位置
     * @param patchPath  补丁位置
     */
    public void start(String oldApkPath, String patchPath) {
        if(TextUtils.isEmpty(oldApkPath) || TextUtils.isEmpty(patchPath)){
            Log.e("TAG"," oldApkPath or patchPath is not empty, abort this function" );
            return;
        }
        this.pathTask.execute(oldApkPath, patchPath);
    }

    public void stop() {
        this.callback = null;
        this.pathTask.cancel(true);
    }

    /**
     * 打补丁任务
     */
    public class PatchTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String oldApkPath = params[0];
            String patchPath = params[1];
            //设置新安装包安装位置及名字 使用补丁包名字
            File patchFile = new File(patchPath);
            String newApkPath = patchFile.getParentFile().getAbsolutePath() + File.separator
                    + patchPath.substring(patchPath.lastIndexOf("/")+1,patchPath.lastIndexOf(".")) + ".apk";
            Log.e("---旧安装包位置---", oldApkPath);
            Log.e("---补丁包位置---", patchPath);
            Log.e("---新补丁包位置---", newApkPath);
            File newApkFile = new File(newApkPath);
//            if (!newApkFile.exists()) {
//                if (patch(oldApkPath, newApkPath, patchPath) != 0) {
//                    newApkPath = "";
//                }
//            }
            return newApkPath;
        }

        @Override
        protected void onPostExecute(String newApkPath) {
            if (callback != null) {
                if (newApkPath.isEmpty()) {
                    callback.onSuccess(newApkPath);
                } else {
                    callback.onFail();
                }
            }
        }
    }

    public interface SmartCallback {
        /**
         * 生成新的补丁包成功
         */
        void onSuccess(String newApkPath);

        /**
         * 生成新的补丁包失败
         */
        void onFail();
    }

    /**
     * native方法 使用路径为oldApkPath的apk与路径为patchPath的补丁包，合成新的apk，并存储于newApkPath
     * <p/>
     * 返回：0，说明操作成功
     *
     * @param oldApkPath 示例:/sdcard/old.apk
     * @param newApkPath 示例:/sdcard/new.apk
     * @param patchPath  示例:/sdcard/xx.patch
     * @return
     */
//    private static native int patch(String oldApkPath, String newApkPath, String patchPath);
}
